package net.maergaiyun.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.maergaiyun.enums.LogTypeEnum;
import net.maergaiyun.model.LogRecord;
import net.maergaiyun.service.LogService;
import net.maergaiyun.util.CommonUtil;
import net.maergaiyun.util.JsonData;
import net.maergaiyun.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@Slf4j
public class LogServiceImpl implements LogService {
    private static final String TOPIC_NAME = "ods_link_visit_topic";

    @Autowired
    private KafkaTemplate kafkaTemplate;

    private static List<String> ipList = new ArrayList<>();

    static {
        // 深圳
        ipList.add("14.197.9.110");
        // 台湾
        ipList.add("120.102.102.11");
        // 北京
        ipList.add("122.12.112.11");
    }

    private static List<String> refererList = new ArrayList<>();

    static {
        refererList.add("https://shenzhen.com");
        refererList.add("https://taiwan.com");
        refererList.add("https://beijing.com");
    }

    private static List<String> userAgentList = new ArrayList<>();

    static {
        userAgentList.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
        userAgentList.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0");
        userAgentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15");
    }


    @Override
    public void recordShortLinkLog(HttpServletRequest request, String shortLinkCode, Long accountNo) {
        Random random = new Random();
//        String ip = CommonUtil.getIpAddr(request);
        int index = random.nextInt(ipList.size());

        String ip = ipList.get(index);
        Map<String, String> headerMap = CommonUtil.getAllRequestHeader(request);
        HashMap<String, String> availableMap = new HashMap<>();
//        availableMap.put("user-agent", headerMap.get("user-agent"));
        String userAgent = userAgentList.get(index);
        availableMap.put("user-agent", userAgent);
//        availableMap.put("referer", headerMap.get("referer"));
        String referer = refererList.get(index);
        availableMap.put("referer", referer);
        availableMap.put("accountNo", String.valueOf(accountNo));

        LogRecord logRecord = LogRecord.builder().event(LogTypeEnum.SHORT_LINK_TYPE.name()).data(availableMap).ip(ip).ts(CommonUtil.getCurrentTimestamp()).bizId(shortLinkCode).build();

        String jsonLog = JsonUtil.obj2Json(logRecord);

        log.info("日志信息: {}", jsonLog);
        kafkaTemplate.send(TOPIC_NAME, jsonLog);
    }
}
